<?php
/**
 * Created by PhpStorm.
 * User: allen
 * Date: 2019/3/8
 * Time: 10:38
 */
namespace app\index\controller;

use think\Controller;
use think\App;
use Naixiaoxin\ThinkWechat\Facade;

class Payment extends Controller{
    protected static $payment  = null;

    public function __construct(App $app = null){
        parent::__construct($app);
        self::$payment = Facade::payment();
    }

    /**
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function wechat_notify(){
        $response = self::$payment->handlePaidNotify(function ($message, $fail) {
            $out_trade_no = $message['out_trade_no'];
            $order = db('orderlist')
                ->where('out_trade_no','eq',$out_trade_no)
                ->find();
            if(!$order){
                return json(['code'=>1,'msg'=>'查询订单不存在']);
            }
            if (!$order || $order->status==2) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') {
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    db('orderlist')->where('id','eq',$order['id'])
                        ->update([
                            'id'=> $order['id'],
                            'payment_trade_no'=>$message['transaction_id'],
                            'finish_time'=>time(),
                            'payment_notify_time'=>$message['time_end'],
                            'payment_trade_status'=>$message['trade_state_desc'],
                            'status'=>1
                        ]);
                    // 用户支付失败
                } elseif ($message['result_code'] === 'FAIL') {
                    db('orderlist')
                        ->update([
                            'id'=>$order['id'],
                            'finish_time'=>time(),
                            'status'=>2
                        ]);
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });
    }
}